<?php
namespace appin\cms\controller\admin;

use app\common\exception\AdminException;
use appin\cms\Admin;

class Column extends Admin
{
    protected $model = \appin\cms\model\Column::class;

    /**
     * 栏目管理
     * @return \think\response\View
     */
    public function index()
    {
        return $this->render();
    }

    /**
     * 栏目数据
     */
    public function datas()
    {
        $data = $this->modelDatas($this->page, $this->limit);
        return json($data);
    }

    /**
     * 编辑HTML文件
     * @return \think\response\View
     * @throws AdminException
     */
    public function html()
    {
        $id     = $this->request->param('id', 0, 'intval');
        $column = $this->model::field('id,pid,mode,template')->where('id', $id)->find();

        if (!$column) {
            throw new AdminException('栏目不存在');
        }

        $temp_name = $column['mode'];
        if (!empty($column['template'])) {
            $temp_name = $column['template'];
        }

        $webHtmlPath = $this->app->getRootPath() . '../appin/cms/template/web/'.$temp_name.'.html';
        $wapHtmlPath = $this->app->getRootPath() . '../appin/cms/template/wap/'.$temp_name.'.html';

        $webHtmlData = '模板文件不存在:'.$webHtmlPath;
        $wapHtmlData = '模板文件不存在:'.$wapHtmlPath;

        if (is_file($webHtmlPath)) {
            $webHtmlData = file_get_contents($webHtmlPath);
        }
        if (is_file($wapHtmlPath)) {
            $wapHtmlData = file_get_contents($wapHtmlPath);
        }
        return $this->render('',[
            'webHtmlData' => $webHtmlData,
            'wapHtmlData' => $wapHtmlData,
            'column' => $column,
        ]);
    }

    /**
     * 保存HTML模板
     */
    public function savehtml()
    {
        $webHtmlData    = $this->request->param('web');
        $wapHtmlData    = $this->request->param('wap');
        $column_id      = $this->request->param('id');
        $column         = $this->model::where('id', $column_id)->field('id,mode,template')->find();

        $temp_name = $column['mode'];
        if ( !empty($column['template']) ) {
            $temp_name = $column['template'];
        }

        $webHtmlPath = $this->app->getRootPath() . '../appin/cms/template/web/'.$temp_name.'.html';
        $wapHtmlPath = $this->app->getRootPath() . '../appin/cms/template/wap/'.$temp_name.'.html';

        if (file_exists($webHtmlPath)) {
            rename($webHtmlPath, $webHtmlPath.'.bak');
        }

        if (file_exists($wapHtmlPath)) {
            rename($wapHtmlPath, $wapHtmlPath.'.bak');
        }

        if (!empty($webHtmlData)) {
            $fp=@fopen($webHtmlPath,"w+");
            @fputs($fp,$webHtmlData);
            @fclose($fp);
        }

        if (!empty($wapHtmlData)) {
            $fp=@fopen($wapHtmlPath,"w+");
            @fputs($fp,$wapHtmlData);
            @fclose($fp);
        }

        return json(['state' => 'success']);
    }
}